import request from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 商品分类接口
 */
export interface GoodsCategory {
  id: number
  category_name: string
  parent_id: number | null
  category_level: number
  category_icon: string
  category_img: string
  category_desc: string
  is_active: boolean
  sort_order: number
  children?: GoodsCategory[]
}

/**
 * 商品基本信息接口（根据实际API响应调整）
 */
export interface GoodsBase {
  goods_id: number
  goods_name: string
  goods_price: string // API返回的是字符串格式
  market_price: string // API返回的是字符串格式
  goods_cover_img: string
  goods_sales: number
  goods_status: number
  goods_intro?: string // 可选字段
  goods_detail_content?: string // 可选字段
  goods_carousel?: string[] // 可选字段
  is_hot?: boolean // 可选字段
  is_new?: boolean // 可选字段
  is_recommend?: boolean // 可选字段
  is_flash_sale?: boolean // 可选字段
  flash_sale_price?: string // 可选字段
  flash_sale_stock?: number // 可选字段
  flash_sale_start_time?: string // 可选字段
  flash_sale_end_time?: string // 可选字段
  category_id?: number // 可选字段
  category_name?: string // 可选字段
  create_time?: string // 可选字段
  update_time?: string // 可选字段
}

/**
 * 商品规格选项接口
 */
export interface GoodsSpecOption {
  option_id: number
  option_name: string
  option_value: string
  option_image?: string
  price_adjustment?: number
  stock: number
}

/**
 * 商品规格接口
 */
export interface GoodsSpec {
  spec_id: number
  spec_name: string
  spec_type: 'text' | 'image'
  options: GoodsSpecOption[]
}

/**
 * 商品参数接口
 */
export interface GoodsParam {
  param_id: number
  param_name: string
  param_value: string
  sort_order: number
}

/**
 * 商品详情接口
 */
export interface GoodsDetail extends GoodsBase {
  specs?: GoodsSpec[]
  params?: GoodsParam[]
  goods_intro: string
  goods_detail_content: string
  goods_carousel: string[]
}

/**
 * 商品分类接口（详情）
 */
export interface GoodsCategoryDetail {
  category_id: number
  category_name: string
  parent: GoodsCategoryDetail | null
  category_level: number
  category_icon: string
  sort_order: number
  status: boolean
}

/**
 * 商品规格接口（详情）
 */
export interface GoodsSpecDetail {
  spec_id: number
  spec_name: string
  spec_value: string
}

/**
 * 商品参数接口（详情）
 */
export interface GoodsParamDetail {
  param_id: number
  param_name: string
  param_value: string
}

/**
 * 秒杀商品接口
 */
export interface FlashSaleItem extends GoodsBase {
  cost_price?: string
  goods_desc?: string
  goods_cover_img_file?: string
  is_flash_sale: boolean
  flash_sale_price: string
  flash_sale_stock: number
  flash_sale_start_time: string
  flash_sale_end_time: string
  create_time?: string
  update_time?: string
}

/**
 * 秒杀商品详情接口
 */
export interface FlashSaleDetail {
  goods_id: number
  goods_name: string
  goods_price: string
  market_price: string
  cost_price: string
  goods_desc: string
  goods_cover_img: string
  goods_cover_img_file: string
  goods_carousel: string[]
  goods_carousel_files: string[]
  goods_stock: number
  goods_sales: number
  goods_status: number
  category: GoodsCategoryDetail
  specs: GoodsSpecDetail[]
  params: GoodsParamDetail[]
  is_flash_sale: boolean
  flash_sale_price: string
  flash_sale_stock: number
  flash_sale_start_time: string
  flash_sale_end_time: string
  create_time: string
  update_time: string
}

/**
 * 分页响应接口
 */
export interface PaginationResponse<T> {
  count: number
  next: string | null
  previous: string | null
  results: T[]
  total_pages?: number
}

/**
 * 商品列表请求参数接口
 */
export interface GoodsListParams {
  page?: number
  page_size?: number
  category_id?: number
  keyword?: string
  sort?: 'price_asc' | 'price_desc' | 'sales' | 'create_time_desc'
  is_hot?: boolean
  is_new?: boolean
  min_price?: number
  max_price?: number
}

/**
 * 热销商品/新品请求参数接口
 */
export interface LimitParams {
  limit?: number
  offset?: number
}

/**
 * 搜索商品请求参数接口
 */
export interface SearchGoodsParams {
  keyword: string
  page?: number
  page_size?: number
  category_id?: number
  sort?: 'price_asc' | 'price_desc' | 'sales' | 'create_time_desc'
}

// ==================== API 服务 ====================

/**
 * 商品API服务
 */
export const goodsApi = {
  /**
   * 获取分类树形结构
   * GET /goods/categories
   */
  getCategories(): Promise<{ data: GoodsCategory[] }> {
    return request({
      url: '/goods/categories/',
      method: 'get',
    })
  },

  /**
   * 获取商品列表
   * GET /goods/list
   * @param params - 查询参数
   */
  getGoodsList(params: GoodsListParams = {}): Promise<{ data: PaginationResponse<GoodsBase> }> {
    const defaultParams: GoodsListParams = {
      page: 1,
      page_size: 10,
    }
    return request({
      url: '/goods/list/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 获取商品详情
   * GET /goods/detail/{goods_id}
   * @param goodsId - 商品ID
   */
  getGoodsDetail(goodsId: number): Promise<GoodsDetail> {
    return request({
      url: `/goods/detail/${goodsId}/`,
      method: 'get',
    })
  },

  /**
   * 获取热销商品
   * GET /goods/hot
   * @param params - 限制数量参数
   */
  // 在 goodsApi 中确保 getHotGoods 返回正确的类型
  getHotGoods(params: LimitParams = {}): Promise<PaginationResponse<GoodsBase>> {
    const defaultParams: LimitParams = {
      limit: 10,
    }
    return request({
      url: '/goods/hot/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 获取新品上架
   * GET /goods/new
   * @param params - 限制数量参数
   */
  getNewGoods(params: LimitParams = {}): Promise<PaginationResponse<GoodsBase>> {
    const defaultParams: LimitParams = {
      limit: 10,
    }
    return request({
      url: '/goods/new/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 商品搜索
   * GET /goods/search
   * @param params - 搜索参数
   */
  searchGoods(params: SearchGoodsParams): Promise<{ data: PaginationResponse<GoodsBase> }> {
    const defaultParams = {
      page: 1,
      page_size: 10,
    }
    return request({
      url: '/goods/search/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 获取商品规格信息
   * GET /goods/{goods_id}/specs
   * @param goodsId - 商品ID
   */
  getGoodsSpecs(goodsId: number): Promise<{ data: GoodsSpec[] }> {
    return request({
      url: `/goods/${goodsId}/specs/`,
      method: 'get',
    })
  },

  /**
   * 获取商品参数信息
   * GET /goods/{goods_id}/params
   * @param goodsId - 商品ID
   */
  getGoodsParams(goodsId: number): Promise<{ data: GoodsParam[] }> {
    return request({
      url: `/goods/${goodsId}/params/`,
      method: 'get',
    })
  },

  /**
   * 获取推荐商品
   * GET /goods/recommend/
   * @param params - 推荐参数
   */
  getRecommendGoods(
    params: { type?: string; limit?: number; offset?: number } = {},
  ): Promise<PaginationResponse<GoodsBase>> {
    const defaultParams = {
      type: 'rating',
      limit: 10,
    }
    return request({
      url: '/goods/recommend/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 获取秒杀商品列表
   * GET /goods/flash-sale/
   * @param params - 分页参数
   */
  getFlashSaleList(
    params: { page?: number; page_size?: number } = {},
  ): Promise<PaginationResponse<FlashSaleItem>> {
    const defaultParams = {
      page: 1,
      page_size: 10,
    }
    return request({
      url: '/goods/flash-sale/',
      method: 'get',
      params: { ...defaultParams, ...params },
    })
  },

  /**
   * 获取秒杀商品详情
   * GET /goods/flash-sale/{goods_id}/
   * @param goodsId - 商品ID
   */
  getFlashSaleDetail(goodsId: number): Promise<FlashSaleDetail> {
    return request({
      url: `/goods/flash-sale/${goodsId}/`,
      method: 'get',
    })
  },
}

// ==================== 工具函数 ====================

/**
 * 格式化价格（将字符串转为数字）
 */
export const formatPrice = (price: string | number): number => {
  if (typeof price === 'number') return price
  return parseFloat(price) || 0
}

/**
 * 检查是否为热卖商品
 */
export const isHotProduct = (product: GoodsBase): boolean => {
  return product.goods_sales > 100 // 可以根据实际业务调整阈值
}

/**
 * 检查是否为新品
 */
export const isNewProduct = (product: GoodsBase): boolean => {
  // 如果有创建时间字段，可以根据时间判断
  if (product.create_time) {
    const createDate = new Date(product.create_time)
    const now = new Date()
    const diffTime = Math.abs(now.getTime() - createDate.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays <= 30 // 30天内为新款
  }
  return false
}

/**
 * 加载商品详情（包含规格和参数）
 */
export const loadGoodsDetailWithSpecs = async (
  goodsId: number,
): Promise<{
  detail: GoodsDetail
  specs: GoodsSpec[]
  params: GoodsParam[]
}> => {
  try {
    const [detailResponse, specsResponse, paramsResponse] = await Promise.all([
      goodsApi.getGoodsDetail(goodsId),
      goodsApi.getGoodsSpecs(goodsId),
      goodsApi.getGoodsParams(goodsId),
    ])

    return {
      detail: detailResponse,
      specs: specsResponse.data,
      params: paramsResponse.data,
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    throw error
  }
}

/**
 * 加载首页数据
 */
export const loadHomePageData = async (): Promise<{
  hotGoods: GoodsBase[]
  newGoods: GoodsBase[]
  categories: GoodsCategory[]
}> => {
  try {
    const [hotGoodsResponse, newGoodsResponse, categoriesResponse] = await Promise.all([
      goodsApi.getHotGoods({ limit: 8 }),
      goodsApi.getNewGoods({ limit: 8 }),
      goodsApi.getCategories(),
    ])

    return {
      hotGoods: hotGoodsResponse.results,
      newGoods: newGoodsResponse.results,
      categories: categoriesResponse.data,
    }
  } catch (error) {
    console.error('加载首页数据失败:', error)
    throw error
  }
}

/**
 * 搜索商品工具函数
 */
export const searchGoodsWithParams = async (
  keyword: string,
  options: Omit<SearchGoodsParams, 'keyword'> = {},
): Promise<PaginationResponse<GoodsBase>> => {
  try {
    const response = await goodsApi.searchGoods({
      keyword,
      page: 1,
      page_size: 12,
      ...options,
    })
    return response.data
  } catch (error) {
    console.error('搜索商品失败:', error)
    throw error
  }
}

// ==================== 默认导出 ====================

export default goodsApi
